#![windows_subsystem="windows"]
#[cfg(windows)]
use std::os::windows::process::CommandExt;


use std::path::Path;
use fltk::enums::Color;
use fltk::{app, button::Button, prelude::*, window::Window};
use std::cell::RefCell;
use std::fs::{
    write,
    read_to_string
};
use std::process::Command;
use std::rc::Rc;
fn open_adb() -> Command{
    let mut tmp = if cfg!(windows){
        Command::new(r"adb.exe")
    }else{
        Command::new("./adb")
    };
#[cfg(windows)]
    tmp.creation_flags(0x08000000);
    tmp
}
fn init() {
    match Path::new("a.json").exists(){
        false => {
            write("a.json", b"114514").unwrap();
            if cfg!(windows) {
                write("adb.exe", include_bytes!(r"adb.exe")).unwrap();
                write("AdbWinApi.dll", include_bytes!("AdbWinApi.dll")).unwrap();
                write("AdbWinUsbApi.dll", include_bytes!("AdbWinUsbApi.dll")).unwrap();
                write("libwinpthread-1.dll", include_bytes!("libwinpthread-1.dll")).unwrap();
            } else {
                write("./adb", include_bytes!("./adb")).unwrap();
                std::fs::create_dir("./lib64/").unwrap();
                Command::new("chmod")
                    .arg("+x")
                    .arg("./adb")
                    .status()
                    .unwrap();
                write("./lib64/libc++.so", include_bytes!("./lib64/libc++.so")).unwrap();
            }
        }
        true => (),
    }
}
fn main() {
    init();
    let app = app::App::default().with_scheme(app::Scheme::Plastic);
    let mut window = Window::new(100, 100, 800, 400, "phigros backup");
    let mut backup = Button::default()
        .with_pos(0, 0)
        .with_size(300, 200)
        .with_label("backup");
    let mut restore = Button::default()
        .with_pos(0, 200)
        .with_size(300, 200)
        .with_label("restore");
    let text = Rc::new(RefCell::new(
        fltk::text::SimpleTerminal::default()
            .with_pos(300, 0)
            .with_size(500, 400),
    ));
    text.borrow_mut().set_text_color(Color::Yellow);
    let text1 = text.clone();
    let text2 = text.clone();
    let hello_txt = "welcome to phi-backup!
develop by bilibili@499415761
";
    text.borrow_mut().append(hello_txt);
    window.end();
    window.show();
    backup.set_callback(move |_| {
        let mut text = text1.borrow_mut();
        text.append("\nadb backup is running.....\nWaiting to start demoen\n");
        text.append("opening phigros.....\n");
        let com1 = open_adb()
            .args(vec!["shell","am","start","-n","com.PigeonGames.Phigros/com.unity3d.player.UnityPlayerActivity"])
            .output()
            .unwrap();
        std::thread::sleep_ms(2000);

        text.append(&String::from_utf8_lossy(&com1.stdout));
        text.append(&String::from_utf8_lossy(&com1.stderr));
        if !com1.status.success(){
            text.append("open phigros failed\n");
            return;
        }
        text.append("请在手机上按下备份\n");
        let com = open_adb()
            .args(vec![
                "backup",
                "-f",
                "tmp.ab",
                "-noapk",
                "-nosystem",
                "-noshard",
                "com.PigeonGames.Phigros",
            ])
            .output()
            .unwrap();
        text.append(&String::from_utf8_lossy(&com.stderr));
        text.append(&String::from_utf8_lossy(&com.stdout));
        if com.status.success() {
            text.append("###adb backup finished###.\n")
        } else {
            text.append("adb failed\n")
        }
    });
    restore.set_callback(move |_| {
        let mut text = text2.borrow_mut();
        text.append("checking backup file\n");
        match read_to_string("tmp.ab"){
            Ok(a) => {
                if a.len() <= 1024{
                    text.append("backup file size error\nplease try to press backup again:(\n");
                    return;
                }
            }
            Err(b) => {
                text.append("error at opening backup file message:\n");
                text.append(&b.to_string());
                return;
            }
        }
        text.append("\nopening phigros.....\n");
        let com1 = open_adb()
            .args(vec!["shell","am","start","-n","com.PigeonGames.Phigros/com.unity3d.player.UnityPlayerActivity"])
            .output()
            .unwrap();
        std::thread::sleep_ms(2000);
        text.append(&String::from_utf8_lossy(&com1.stdout));
        text.append(&String::from_utf8_lossy(&com1.stderr));
        if !com1.status.success(){
            text.append("open phigros failed\n");
            return;
        }
        text.append("adb restore is running.....\n请在手机上按下恢复备份\n");
        let com = open_adb()
            .args(vec!["restore", "tmp.ab"])
            .output()
            .unwrap();

        text.append(&String::from_utf8_lossy(&com.stderr));
        text.append(&String::from_utf8_lossy(&com.stdout));
        if com.status.success() {
            text.append("###adb restore finished###.\n")
        } else {
            text.append("adb restore failed\n")
        }
    });
    app.run().unwrap();
}
